var express = require('express');
var router = express.Router();

var COS = require('cos-nodejs-sdk-v5');

var express = require("express");
var router = express.Router();

const alipaySdk = require("./alipay");
const AlipayFormData = require("alipay-sdk/lib/form");
const nodemailer = require("nodemailer");
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
const { randomCode, sendCode } = require("../tools/sendCode");

let jwt = require('jsonwebtoken')
let {
  userModel,
  relationModel, familyModel,
  ChildItem,
  Item,
  chatcomModel,
  Hospital,
  Flag,
  Person,
  OutpatientPayment,
} = require('../model/model')

//邮箱验证码
const { send, createSixNum } = require("./util");
const NodeCache = require("node-cache");
const myCache = new NodeCache();

//渲染信息表
router.get('/user', async (req, res) => {
  let user = await userModel.find().populate('relationid')
  res.send({
    code: 200,
    masg: '成功',
    user
  })
})
//渲染关系表
router.get('/relation', async (req, res) => {
  let relation = await relationModel.find()
  res.send({
    code: 200,
    masg: '成功',
    relation
  })
})
//渲染亲属表
router.get('/family', async (req, res) => {
  let family = await familyModel.find().populate('userid')
  res.send({
    code: 200,
    masg: '成功',
    family
  })
})
//添加信息
// router.post('/adduser', async (req, res) => {
//   await userModel.create(req.body)
//   console.log(req.body);
//   res.send({
//     code: 200,
//     masg: '成功',
//   })
// })
//添加亲属信息
router.post('/addfamily', async (req, res) => {
  await familyModel.create(req.body)
  console.log(req.body);
  res.send({
    code: 200,
    masg: '成功',
  })
})

//修改信息
router.put('/upuser', async (req, res) => {
  let { _id } = req.body
  await userModel.updateOne({ _id }, req.body)
  res.send({
    code: 200,
    masg: '成功',
  })
})
//删除信息
router.delete('/deluser', async (req, res) => {
  let { _id } = req.body
  await userModel.deleteOne({ _id })
  res.send({
    code: 200,
    masg: '成功',
  })
})
//删除亲属信息
router.delete('/delfamily', async (req, res) => {
  let { _id } = req.query
  await familyModel.deleteOne({ _id })
  res.send({
    code: 200,
    masg: '成功',
  })
})
// 图片审核
router.post('/shen', async (req, res) => {
  let { url, file } = req.body
  const cos = new COS({
    SecretId: 'AKID43EH8kM1YwIzUvDG6lBMPq2AAvRijUDo',
    SecretKey: 'ThgRzIEyjOo0zmKfqqdEeqrfFblhQB1o',
  });
  const config = {
    // 需要替换成您自己的存储桶信息
    Bucket: '3065060034-1326451460', // 存储桶，必须
    Region: 'ap-beijing', // 存储桶所在地域，必须字段
  };
  cos.request({
    Bucket: config.Bucket, Region: config.Region, Method: 'GET', Key: file,  // 存储桶内的图片文件，必须字段
    Query: {
      'ci-process': 'sensitive-content-recognition', // * 固定值，必须
      'biz-type': 'e7864e636a8b11efbd6d5254000fc30f', // * 审核类型，非必须如果不填是默认的,判断的类型少
      'detect-url': '', // * 审核任意公网可访问的图片链接，非必须
      'interval': 5, // * 审核 GIF 动图时，每隔interval帧截取一帧，非必须
      'max-frames': 5, // * 审核 GIF 动图时，最大截帧数，非必须
      'large-image-detect': '0', // * 是否需要压缩图片后再审核，非必须
      'dataid': '123', // * 自定义图片标识，非必须
    },
  }, function (err, data) {
    if (err) {
      // 处理请求出错
      console.log(err, '失败');
    } else {
      // 处理请求成功 
      const data1 = transformData(data.RecognitionResult)
      // console.log(data1.label,11111111111111111)
      // 将英文装换为中文
      const tran = translate(data1.label)

      if (data1.score > 70) {
        translate(data1.label).then(translatedText => {
          res.send({
            status: 400,
            data: data1,
            msg: '有违规内容',
            translatedText: translatedText
          })
        }).catch(err => {
          console.log(err)
        })
      } else {
        res.send({
          status: 200,
          data: data1,
          msg: '没有违规内容'
        })
      }

    }
  });
})

// 转换函数
function transformData(data) {
  return {
    dataId: data.DataId,
    jobId: data.JobId,
    label: data.Label,
    subLabel: data.SubLabel,
    score: data.Score,
    category: data.Category,
    object: data.Object,
    state: data.State,
    Text: data.Text,
    terrorismScore: data.TerrorismInfo.Score,
  };
}

router.post('/upload1', async (req, res) => {
  var Form = new multiparty.Form();
  Form.uploadDir = 'upload'
  Form.parse(req, function (err, fields, files) {
    console.log(files.file[0].path, 111111111111111)
    let image = 'http://localhost:3000/' + files.file[0].path
    res.send({ code: 200, data: image })
  })
})

async function translate(data) {
  const tencentcloud = require("tencentcloud-sdk-nodejs-tmt"); // 导入对应产品模块
  const TmtClient = tencentcloud.tmt.v20180321.Client;
  const clientConfig = {
    credential: {
      secretId: "AKID43EH8kM1YwIzUvDG6lBMPq2AAvRijUDo",
      secretKey: "ThgRzIEyjOo0zmKfqqdEeqrfFblhQB1o",
    },
    region: "ap-beijing",
    profile: {
      httpProfile: {
        endpoint: "tmt.tencentcloudapi.com",
      },
    },
  };
  // 实例化要请求产品的client对象,clientProfile是可选的
  const client = new TmtClient(clientConfig);
  const params = {
    "SourceText": data,
    "Source": "en",
    "Target": "zh",
    "ProjectId": 0,
    "UntranslatedText": ""
  };

  return client.TextTranslate(params).then(
    (data) => {
      console.log(data);
      return data.TargetText
    },
    (err) => {
      console.error("error", err);
    }
  );

}


//邮箱验证码
let smsAll = null;
let phonecodes = null;

//发送邮件
router.get("/getemail", async (req, res) => {
  try {
    const { mail } = req.query; //获取前端传过来的邮箱
    console.log(mail);
    let code = createSixNum(); // 随机验证码

    // 将code存入缓存
    myCache.set("code", code, 300); // 缓存5分钟

    send(mail, code) //发送邮件的函数,传入邮箱和6位验证码
      .then(() => {
        res.json({ msg: "验证码发送成功", code: 200 });
      })
      .catch((err) => {
        console.error(err);
        res.json({ msg: "验证码发送失败" });
      });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "邮件发送失败" });
  }
});

router.post("/add", (req, res) => {
  OutpatientPayment.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
router.get("/OutpatientPayment", async (req, res) => {
  let data = await OutpatientPayment.find();
  res.send({
    code: 200,
    msg: "查询成功",
    data,
  });
});

// 支付
router.post("/zhi", async (req, res) => {
  let data11 = req.body;
  let no = Date.now();
  const formData = new AlipayFormData();
  formData.setMethod("get");
  formData.addField("returnUrl", `http://localhost/orderconfirm`);
  formData.addField("bizContent", {
    outTradeNo: no,
    productCode: "FAST_INSTANT_TRADE_PAY",
    totalAmount: data11.price,
    subject: data11.name,
    body: data11.time,
  });
  const result = await alipaySdk.exec(
    "alipay.trade.page.pay",
    {},
    { formData: formData }
  );
  res.send({
    success: "true",
    code: 200,
    result: result,
  });



  router.post('/login', async (req, res) => {
    let { username } = req.body
    let user = await userModel.findOne({ username })
    if (user) {
      res.send({ status: 200, msg: '登录成功', user })
    }
    else {
      res.send({ status: 400, msg: '用户名不存在' })
    }
  })
});
router.post('/register', async (req, res) => {
  let { username } = req.body
  let user1 = await userModel.findOne({ username })
  console.log(user1)
  if (user1) {
    res.send({
      status: 400,
      msg: '用户名已存在'
    })
  } else {
    userModel.create(req.body)
    res.send({
      status: 200,
      msg: '注册成功'
    })
  }

})



//验证码登录
router.post("/SMS", async (req, res) => {
  let { phone } = req.body;
  let code = randomCode(4); //生成6位数字随机验证码
  sendCode(phone, code, function (success) {
    if (success) {
      res.send({
        code: 200,
        msg: "验证码发送成功",
        data: code,
      });
    } else {
      res.send("短信验证码发送失败");
    }
  });
});
router.post("/code_login", async (req, res) => {
  let { phone, code, password } = req.body;
  console.log(phone, code, password);
  let result = await userModel.findOne({ phone });
  let token = ' Bearer' + ' ' + jwt.sign({ phone }, "secretKey", { expiresIn: "1d" }
  );
  await userModel.updateOne({ phone }, { password: '123456' });
  if (result) {
    res.send({
      code: 200,
      Toast: "登录成功",
      result,
      token
    });
  } else {
    res.send({
      code: 400,
      Toast: "登录失败",
    });
  }
});


//手机号密码登录
router.post("/loginn", async (req, res) => {
  let { password, phone } = req.body;
  console.log(password, phone);
  let result = await userModel.findOne({ phone, password });
  console.log(result);
  let token = ' Bearer' + ' ' + jwt.sign({ phone }, "secretKey", { expiresIn: "1d" });
  if (result) {
    res.send({
      code: 200,
      Toast: "登录成功",
      result,
      token
    });
  } else {
    res.send({
      code: 400,
      Toast: "登录失败",
    });
  }
});

// 人脸识别
router.post("/faceLogin", async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.b64;
  const IaiClient = tencentcloud.iai.v20200303.Client;
  try {
    const clientConfig = {
      credential: {
        //自己的腾讯secretId
        secretId: "AKIDSltsjRwDVjsHjBWknqytnaaMxKTRCl7J",
        //自己的腾讯密匙
        secretKey: "CE6nNCyc8WiuBSav8FBHQTKPSTaZdyRm",
      },
      region: "ap-beijing", //地域参数（华北地区北京）+
      profile: {
        httpProfile: {
          endpoint: "iai.tencentcloudapi.com",
        },
      },
    };
    const client = new IaiClient(clientConfig);
    const params1 = {
      "Image": b64,
      "FaceModelVersion": "3.0" //人脸识别所用的算法模型版本
    }
    client.DetectLiveFaceAccurate(params1).then(
      async (data) => {
        if (data.Score > 87) {
          const params = {
            "GroupIds": [  //你创建的人员库ID
              "111"
            ],
            "Image": b64,  //图片的base64格式编码
            "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
            "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
            "FaceMatchThreshold": 90,  //人脸对比度设置为大于90才可
          };
          let doc = await client.SearchFaces(params) // doc为人脸识别后的返回信息
          if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
            let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
            console.log(personName, 'personNume');
            let user = await userModel.find({ username: personName })
            console.log(user[0])
            if (user.length != 0) {
              //生成token
              let token = jwt.sign({ name: personName }, "face", { expiresIn: '1d' })
              res.send({
                code: 200,
                msg: "登录成功！",
                token,
                user: user[0]
              })
            }
          } else {
            res.send({
              code: 401,
              msg: '人脸库无此人！'
            })
            return false
          }

        } else {
          res.send({
            code: 401,
            msg: '请使用活物人脸识别'
          })
        }
      },
      (err) => {
        console.error("error", err);
      }
    );
  } catch (err) {
    console.log(err);
  }
});

//注册
router.post("/register", async (req, res) => {
  let { username, phone, email } = req.body;
  console.log(req.body);
  let Phone = await userModel.findOne({ phone });
  let Email = await userModel.findOne({ email });
  let Username = await userModel.findOne({ username });
  if (Username) {
    res.send({
      code: 400,
      msg: "该用户名已被绑定",
    });
    return;
  }
  if (Phone) {
    res.send({
      code: 400,
      msg: "该手机号已被绑定",
    });
    return;
  }
  if (Email) {
    res.send({
      code: 400,
      msg: "该邮箱已被绑定",
    });
    return;
  } else {
    //用户不存在进行注册
    userModel.create(req.body);
    console.log();
    res.send({
      code: 200,
      msg: "注册成功! 去登入",
    });
  }
});




// 赵子航
// 添加科室信息
router.post('/ChildAdd', async (req, res) => {
  let depart = await ChildItem.create(req.body)
  res.send({
    depart,
    code: 200
  })
});
// 添加科室信息
router.post('/ItemAdd', async (req, res) => {
  let depart = await Item.create(req.body)
  res.send({
    depart,
    code: 200
  })
});




// 获取科室信息
router.get('/depart', async (req, res) => {
  let { text } = req.query
  depart = await Item.find().populate('children')
  res.send({
    depart,
    code: 200
  });

})
// 获取科室
router.get('/childLs', async (req, res) => {
  depart = await ChildItem.find()
  res.send({
    depart,
    code: 200
  });

})


router.post('/HospitalAdd', async (req, res) => {
  let hospital = await Hospital.create(req.body)
  res.send({
    hospital,
    code: 200
  })
})
router.post('/PersonAdd', async (req, res) => {
  let person = await Person.create(req.body)
  res.send({
    person,
    code: 200
  })
})
// 添加锦旗
router.post('/FlagAdd', async (req, res) => {
  let flag = await Flag.create(req.body)
  res.send({
    flag,
    code: 200
  })
})

// 获取医生信息
router.get('/Person', async (req, res) => {
  let { id, text } = req.query


  let queryLd = []
  if (id) {
    queryLd.push({ _id: id })
  }
  if (text) {
    queryLd.push({ child: text })
  }


  let person = []
  if (queryLd.length != 0) {
    person = await Person.find({ $or: queryLd }).populate('flag').populate('hospital')
  } else {
    person = await Person.find().populate('flag').populate('hospital')
  }


  res.send({
    person,
    code: 200
  })
})




// 锦旗
router.get('/Flag', async (req, res) => {
  let { title } = req.query

  let queryLs = []
  if (title) {
    queryLs.push({ title: title })
  }

  let flag = []
  if (queryLs.length != 0) {
    flag = await Flag.find({ $and: queryLs })
  } else {
    flag = await Flag.find()
  }
  res.send({
    flag,
    code: 200
  })
})

// 修改关注
router.post('/upStatus', async (req, res) => {
  let { id, userid, istrue } = req.body
  let doctobj = await Person.findOne({ _id: id })
  let looklis = doctobj.followers
  if (istrue) {
    looklis = looklis.filter(item => item != userid)
    console.log(looklis, "looklis")
    await Person.updateOne({ _id: id }, { followers: looklis })
    res.send({
      code: 200,
      msg: "取消关注success"
    })
    return false
  } else {
    !looklis.some(item => item == userid) && looklis.push(userid)
    await Person.updateOne({ _id: id }, { followers: looklis })
    res.send({
      code: 200,
      msg: "关注success"
    })
    return false
  }
})

// 点赞
router.post('/uplikes', async (req, res) => {
  let { id, userid, islike } = req.body
  let likeObj = await chatcomModel.findOne({ _id: id })
  // console.log(likeObj)
  let likeslis = likeObj.likes
  if (islike) {
    likeslis = likeslis.filter(item => item != userid)
    await chatcomModel.updateOne({ _id: id }, { likes: likeslis })
    res.send({
      code: 200,
      msg: '取消点赞'
    })
    return false
  } else {
    !likeslis.some(item => item.userid) && likeslis.push(userid)
    await chatcomModel.updateOne({ _id: id }, { likes: likeslis })
    res.send({
      code: 200,
      msg: '成功点赞'
    })
    return false
  }

})


// 评价无限极
router.post('/commentAdd', async (req, res) => {
  console.log(req.body)
  let data = []
  if (req.body.pid) {
    data = await chatcomModel.create(req.body)
  } else {
    delete req.body.pid
    data = await chatcomModel.create(req.body)
  }
  res.send({
    data,
    code: 200,
    meg: '评论成功'
  })
})


// 获取评价无限极
router.get('/chatCom', async (req, res) => {
  let menu = await chatcomModel.find().lean().populate('person').populate('userid')
  let menuObj = {}
  menu.forEach(item => {
    menuObj[item._id] = item
  })

  data = []

  menu.forEach(ele => {
    if (!ele.pid) {
      data.push(ele)

    } else {
      if (menuObj[ele['pid']] && !menuObj[ele['pid']]['children']) {
        console.log(menuObj[ele['pid']] && !menuObj[ele['pid']]['children'])
        menuObj[ele['pid']]['children'] = []
      }
      if (menuObj[ele['pid']]) {
        console.log(menuObj[ele['pid']])
        menuObj[ele['pid']]['children'].push(ele)
        console.log(menuObj)
      }
    }
  })
  res.send({
    data,
    code: 200
  })
})


router.get('/doctorLists', async (req, res) => {
  let data = await Person.find().populate('flag').populate('hospital')
  res.send({
    data,
    code: 200,
    msg: 'success'
  })
})


module.exports = router;
